package com.carl.zlds.interceptor;

import com.carl.zlds.tool.exception.GlobalException;
import com.carl.zlds.annotation.Login;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.net.URI;

/**
 * @author lq
 */
@Slf4j
@Component
public class SecurityInterceptor implements HandlerInterceptor {
    private final Authenticator authenticator;

    @Autowired
    public SecurityInterceptor(Authenticator authenticator) {
        this.authenticator = authenticator;
    }

    private static String[] GUEST_URI = {"/swagger-ui.html", "/configuration/ui", "/swagger-resources", "/csrf", "/error", "/webjars"};

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        URI uri = new URI(httpServletRequest.getRequestURI());
        String path = uri.getPath();

        // 如果是游客链接直接跳过
        for (String guestUri : GUEST_URI) {
            if (path.contains(guestUri)) {
                return true;
            }
        }

        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            Login login = method.getAnnotation(Login.class);
            if (login == null || login.needToken()) {
                // 如果注解为null 或者需要token, 说明需要拦截
                authenticator.process(httpServletRequest);
            }
        }

        return true;
    }

    public interface Authenticator {
        void process(HttpServletRequest httpServletRequest);
    }

    public static String getRequiredParam(HttpServletRequest httpServletRequest, String key) {
        if (!httpServletRequest.getParameterMap().containsKey(key)) {
            throw new GlobalException(GlobalException.ERROR_PARAM_NOT_SET, key + " not set");
        }

        return httpServletRequest.getParameter(key);
    }
}

